import os

import wx
import wx.stc

import fm
from base import *

from debug  import here

import mainpanel

settings=fm.settings

settings['status_bar.default_text']='Ready'
settings['status_bar.short_duration_text_milliseconds']=3000

def reset_status_text():
	fm.main_frame.SetStatusText(settings['status_bar.default_text'])

def set_status_text(string):
	fm.main_frame.SetStatusText(string)
	
def short_duration_status_text(string,milliseconds=settings['status_bar.short_duration_text_milliseconds']):
	set_status_text(string)
	wx.CallLater(milliseconds,reset_status_text)

"""	
def status_bar_set_mode_name(name): # ?? todo
	fm.main_frame.status_bar_set_mode_name(name) 
"""

class MainFrame(wx.Frame):
	"""
	This class is responsible for menus, and toolbar.
	MainPanel handles title and status bar.
	"""

	STATUS_BAR_RIGHT_FIELD=1


	def __init__(me,size=(700,700)):		
		wx.Frame.__init__(me,parent=None,title='Farmhand',size=size)
				
		me.main_panel=mainpanel.MainPanel(me)
		
		# - events
		
		me.Bind(wx.EVT_CLOSE,me.OnApplicationClose)
		
		me.main_panel.events.ActiveDocSwitch+=me.on_active_doc_switch
		
		# - menus
		
		def local_menu_add(menu,label,handler,id=None,help_str="",kind=wx.ITEM_NORMAL):
			if label=='---':
				menu.AppendSeparator()
				return
			if id is None:
				id=wx.NewId()
			item=menu.Append(id,label,help_str,kind)
			me.Bind(wx.EVT_MENU,handler,id=id)
			return item
			
		menubar=wx.MenuBar()
		me.SetMenuBar(menubar)
		
		file_menu=wx.Menu()
		menubar.Append(file_menu,"&File")
		for       label,              handler,      id,             help_str in (
				( "&New\tCtrl-N",     me.OnNew,     wx.ID_NEW,     "Bust it open"      ),
				( "&Open...\tCtrl-O", me.OnOpen,    wx.ID_OPEN,    "Whip it out"       ),
				( "?? Recent",       None,  None, ''), # ??
				( "---",              '---',        '---',         '---'               ),
				( "&Save\tCtrl-S",    me.OnSave,    wx.ID_SAVE,    "Save this mother"  ),
				( "?? Rename...",       None,  None, ''), # ??
				( "?? Fork...",       None,  None, ''), # ??
				( "Save As...",       me.OnSaveAs,  wx.ID_SAVEAS,  "Save file with a new name" ),
				( "?? Save a Copy...",       None,  None, ''), # ??
				( "?? Save All",       None,  None, ''), # ??
				( "---",              '---',        '---',         '---'               ),
				( "&Close\tCtrl-W",   me.OnClose,   wx.ID_CLOSE,   "Close file"        ),
				( "&Exit\tCtrl-X",    me.OnExit,    wx.ID_EXIT,    "Quit"              )
				):
			local_menu_add(file_menu,label,handler,id,help_str)
			
		edit_menu=wx.Menu()
		menubar.Append(edit_menu,"&Edit")
		for       label,              handler,      id in (
				( "&Undo\tCtrl-Z",    me.OnUndo,    wx.ID_UNDO     ),
				( "&Redo\tShift-Ctrl-Z",me.OnRedo,  wx.ID_REDO     ),
				( "---",              '---',        '---'          ),
				( "Cut\tCtrl-X",      me.OnCut,     wx.ID_CUT      ),
				( "&Copy\tCtrl-C",    me.OnCopy,    wx.ID_COPY     ),
				( "&Paste\tCtrl-V",   me.OnPaste,   wx.ID_PASTE    ),
				( "---",              '---',        '---'          ),
				( "&Find...\tCtrl-F", me.OnFind,    wx.ID_FIND     ),
				( "Find &Next\tCtrl-G",me.OnFindNext,wx.NewId()    ),
				( "Find &Prev\tCtrl-R",me.OnFindPrev,wx.NewId()    ),
				):
			local_menu_add(edit_menu,label,handler,id)
			
		doc_menu=wx.Menu()
		menubar.Append(doc_menu,"&Doc")
	
		eol_menu=wx.Menu()
		doc_menu.AppendMenu(wx.NewId(),'Eol Mode',eol_menu)
		me.id_eol_mode_Mac,me.id_eol_mode_Win,me.id_eol_mode_Unix=wx.NewId(),wx.NewId(),wx.NewId()
		me.menu_item_eol_mac=local_menu_add(eol_menu,'Mac "\\r"',me.OnEolModeChange,me.id_eol_mode_Mac,'set end of line mode',kind=wx.ITEM_RADIO)
		me.menu_item_eol_win=local_menu_add(eol_menu,'Win "\\r\\n"',me.OnEolModeChange,me.id_eol_mode_Win,'set end of line mode',kind=wx.ITEM_RADIO)
		me.menu_item_eol_unix=local_menu_add(eol_menu,'Unix "\\n"',me.OnEolModeChange,me.id_eol_mode_Unix,'set end of line mode',kind=wx.ITEM_RADIO)
		
		settings_menu=wx.Menu()
		menubar.Append(settings_menu,"&Settings")
		r=local_menu_add(settings_menu,'Show Line Numbers',me.OnShowLineNumbers,kind=wx.ITEM_CHECK)
		if settings['show_line_numbers']: r.Check()
		r=local_menu_add(settings_menu,'Wrap',me.OnWrap,kind=wx.ITEM_CHECK)
		if settings['wrap']: r.Check()
		local_menu_add(settings_menu,'---',None,None)
		local_menu_add(settings_menu,'Edit Settings File',me.OnOpenSettingsFile)
		local_menu_add(settings_menu,'Open Example Settings',me.OnOpenExampleSettings)
		
		helpmenu=wx.Menu()
		menubar.Append(helpmenu,'&Help')
		local_menu_add(helpmenu,'&About...',me.OnAbout,wx.ID_ABOUT)
		wx.App_SetMacHelpMenuTitleName("&Help") # ?? doesn't appear to work, get two help menus, perhaps once this is packaged with p2app...
					
		# - </menus>
		
		sb=wx.StatusBar(me)
		sb.SetFieldsCount(me.STATUS_BAR_RIGHT_FIELD+1)
		sb.SetStatusWidths([-2,-1])
		me.SetStatusBar(sb)

	def SetStatusTextRightField(me,string):
		me.SetStatusText(string,me.STATUS_BAR_RIGHT_FIELD)

	# - menu handlers
		
	# file menu	
	def OnNew(me,e):      me.main_panel.new()
	def OnOpen(me,e):     me.main_panel.open()
	def OnSave(me,e):     me.main_panel.save()
	def OnClose(me,e):    me.main_panel.close()
	def OnSaveAs(me,e):   me.main_panel.save_as()
	
	def OnExit(me,e):
		can_veto=True
		me.Close(can_veto)
		
	# edit menu
	def OnCut(me,e):     me.main_panel.cut()
	def OnUndo(me,e):    me.main_panel.undo()
	def OnCopy(me,e):    me.main_panel.copy()
	def OnFind(me,e):    me.main_panel.find()
	def OnFindNext(me,e):me.main_panel.find_next()
	def OnFindPrev(me,e):me.main_panel.find_prev()
	def OnRedo(me,e):    me.main_panel.redo()
	def OnPaste(me,e):   me.main_panel.paste()
	
	# doc menu
	def OnEolModeChange(me,e):
		id=e.GetId()
		
		if id==me.id_eol_mode_Mac: mode='mac'
		elif id==me.id_eol_mode_Win: mode='win'
		elif id==me.id_eol_mode_Unix: mode='unix'
		else: assert 0
		
		me.main_panel.set_eol_mode(mode)
		
	# settings menu
	def OnShowLineNumbers(me,e): settings['show_line_numbers']=e.IsChecked()
	def OnWrap(me,e): settings['wrap']=e.IsChecked()
	def OnOpenSettingsFile(me,e):  me.main_panel.open(fm.get_user_settings_module_path())
	def OnOpenExampleSettings(me,e): me.main_panel.open(fm.get_default_settings_dump_path())
		
	# help menu
	def OnAbout(me,e):
		info=wx.AboutDialogInfo()
		info.Name='Farmhand'
		info.Version=fm.VERSION
		info.Description='Farmhand Editor\n---\n'+fm.version_summary()
		info.WebSite=('http://dan-sg.com/farmhand','Farmhand Homepage')
		wx.AboutBox(info)
		
	# - </menu handlers>
	
	# - fm events
	
	def on_active_doc_switch(me,e):
		mode=e.new_doc.get_eol_mode()
		#print mode
		if mode=='mac':me.menu_item_eol_mac.Check()
		elif mode=='win':me.menu_item_eol_win.Check()
		elif mode=='unix':me.menu_item_eol_unix.Check()
		else: assert 0
	
	def OnApplicationClose(me,e):
		if me.main_panel.exit()<>OK:
			e.Veto()
			return
		fm.settings.on_application_close()
		fm.persistent_state.on_application_close()
		
		me.Destroy()
		
	# - </fm events>
